package com.buaa.daas.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

@Controller
public class LogoutController {

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/logout")
    String logout(HttpServletRequest request){
        String token = "";
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            for (Cookie cookie : cookies) {
                if("token".equals(cookie.getName())){
                    token = cookie.getValue();
                }
            }

            if(!StringUtils.isBlank(token)){
                Object tokenValue = redisTemplate.opsForValue().get(token);
                if(tokenValue!=null){
                    redisTemplate.delete(token);
                }
            }
        }

        return "redirect:/login";
    }

}
